import { Injectable } from '@nestjs/common';
import { cmdExec, delay } from '../utils/tool';
import { usb } from 'usb';
import { Observable } from 'rxjs';

const getDevList = async () => {
  const list = await cmdExec('hdc list targets').then((res) => {
    return res
      .split(/\r?\n/)
      .filter((item: string) => item && !item.includes('Empty'));
  });
  return (list || []).map((SN) => ({ id: SN, link_type: 'hdc' }));
};

@Injectable()
export class DeviceListService {
  getDeviceList(): Observable<MessageEvent> {
    return new Observable<any>((observer) => {
      getDevList().then((list) => {
        observer.next({ data: list });
      });
      usb.on('attach', async () => {
        let list = await getDevList();
        if (!list || !list.length) {
          let i = 0;
          while (i < 5 && list.length === 0) {
            await delay(500);
            list = await getDevList();
            i++;
          }
        }
        observer.next({ data: list });
      });
      usb.on('detach', async () => {
        const list = await getDevList();
        observer.next({ data: list });
      });
    });
  }
}
